﻿using Basic.FormCollect;
using Basic.FormRemoteModel;
using Basic.FormRemoteModel.Form.Model;
using Basic.FormService.Helper;
using Basic.FormService.Interface;
using Basic.FormService.Model;
using WeDonekRpc.Helper;

namespace Basic.FormService.Extend
{
    internal class PhyFormColSelectService : IPhyFormColSelectService
    {
        private readonly IPhysicalTableCollect _PhyTable;
        private readonly IPhysicalColumnCollect _PhyColumn;

        public PhyFormColSelectService ( IPhysicalTableCollect phyTable, IPhysicalColumnCollect phyColumn )
        {
            this._PhyTable = phyTable;
            this._PhyColumn = phyColumn;
        }

        public StructureColumn[] Gets ( long formId, FormGetParam param )
        {
            FormRecordDataType[] dataType = param.DataType.GetDataType();
            PhyTableCol[] cols = this._PhyColumn.GetsByFormId<PhyTableCol>(formId, param.FuncType, dataType);
            if ( cols.IsNull() )
            {
                return Array.Empty<StructureColumn>();
            }
            if ( !param.TableId.IsNull() )
            {
                cols = cols.FindAll(c => param.TableId.Contains(c.PhyTableId));
                if ( cols.IsNull() )
                {
                    return Array.Empty<StructureColumn>();
                }
            }
            PhyTable[] tables = this._PhyTable.Gets<PhyTable>(cols.ConvertAll(c => c.PhyTableId));
            if ( tables.IsNull() )
            {
                return Array.Empty<StructureColumn>();
            }
            return tables.ConvertAll(a =>
            {
                StructureColumn col = new StructureColumn
                {
                    Id = a.Id,
                    Label = a.TableLabel,
                    Type = a.TableType == FormTableType.多行列表 ? StructureType.Table : StructureType.Single
                };
                col.Children = cols.Where(c => c.PhyTableId == a.Id).Select(this._FormatCol).ToArray();
                return col;
            });
        }
        private StructureColumn _FormatCol ( PhyTableCol col )
        {
            StructureColumn column = new StructureColumn
            {
                Id = col.Id,
                Label = col.Label,
                Name = col.Name,
                Type = StructureType.Column,
                DataType = col.DataType,
                FuncType = col.FuncType.ToDataFuncType(),
            };
            if ( column.FuncType == DataFuncType.选项值 )
            {
                column.Items = col.ColumnSet.Items.ToArray();
            }
            else if ( column.FuncType == DataFuncType.字典项 || column.FuncType == DataFuncType.树形字典 )
            {
                column.DicId = col.ColumnSet.DicId;
            }
            return column;
        }
    }
}